<?php


namespace app\api\controller\v1;


use app\api\model\BaseModel;
use app\api\model\Image;
use app\api\model\UserRealAuth;
use app\lib\exception\ParameterException;
use app\api\service\Token as TokenService;

class ImgUpdate extends BaseModel
{
    /**
     * 身份证添加水印
     */
    public function imgUpdateWord($status,$img_id)
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $img = Image::get($img_id);
        $words_result = $this->getAccessToken($img['url']);
        if($status == 1) {
            UserRealAuth::where('openid',$openid)->update([
                'just_msg_json' => json_encode($words_result)
            ]);
        } else {
            UserRealAuth::where('openid',$openid)->update([
                'back_msg_json' => json_encode($words_result)
            ]);
        }
        $imgs = explode('public',$img['url']);
        $image = \think\Image::open(config('setting.cms_img_url').$imgs[1]);
        $image->text('本照片只用作甜茶派对实名认证使用',config('setting.img_url').'/WeiRuanYaHei.ttf',40,'#ffffff',\think\Image::WATER_CENTER,0,0)->save(config('setting.cms_img_url').$imgs[1]);
        return  Image::get($img_id);
    }

    private function getAccessToken($img_url)
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = 'WVzL8hgtKqLYBO7ao8EuYR88';
        $post_data['client_secret'] = 'qbGx4zqzPofzEFjDyzAABOYMymh9VvTq';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = https_post($url,$post_data);
        $res = json_decode($res,true);
        return $this->changeImg($res,$img_url);
    }

    private function changeImg($access_token,$img_url)
    {
        $token = $access_token['access_token'];
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $token;
        $img = file_get_contents($img_url);
        $img = base64_encode($img);
        $bodys = array(
            'id_card_side' => "front",
            'image' => $img
        );
        $res = https_post($url, $bodys);
        $res = json_decode($res,true);
        $loginFail = array_key_exists('words_result', $res);
        if($loginFail) {
            return $res;
        } else {
            throw new ParameterException([
                'msg' => [
                    'img' => '请上传正确的身份证照片'
                ]
            ]);
        }
    }
}